package com.lincoln.framework.bean;

import com.lincoln.framework.exception.ErrorFormatException;
import com.lincoln.framework.interfaces.BaseDecoder;
import com.lincoln.framework.interfaces.BaseProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 处理带消息号的消息解码器
 *
 * @author lincoln
 */
public class AbstractMsgNoDecoder extends BaseDecoder {
    private static Logger logger = LoggerFactory.getLogger(AbstractMsgNoDecoder.class);

    /**
     * <pre>
     * int类型，占据4个字节.
     * 最小帧长度为
     * </pre>
     */
    public final int BASE_LENGTH = 6;
    public final int MAX_LENGTH = 1024;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        // 可读长度必须大于基本长度
        if (buffer.readableBytes() >= BASE_LENGTH) {
            // 防止socket字节流攻击
            // 防止，客户端传来的数据过大
            // 因为，太大的数据，是不合理的
            if (buffer.readableBytes() > MAX_LENGTH) {
                buffer.skipBytes(buffer.readableBytes());
            }

            byte[] byteArray = new byte[buffer.readableBytes()];
            buffer.readBytes(byteArray);

            // 读取data数据
            try {
                BaseProtocol protocol = new AbstractMsgNoProtocol(byteArray);
                out.add(protocol);
            } catch (NegativeArraySizeException e) {
                logger.error("错误:收到的帧长度为负数");
            } catch (ErrorFormatException e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 将gbk转utf8
     *
     * @param gbkStr
     * @return
     */
    public static String gbk2utf8(String gbkStr) {
        try {
            return new String(gbk2utf8Bytes(gbkStr), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return gbkStr;
        }
    }

    /**
     * 将gbk字符串转成utf8字节集
     *
     * @param gbkStr
     * @return
     */
    public static byte[] gbk2utf8Bytes(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }
}
